package com.xiaomage.localbroadcasereceiverdemo

import android.app.Activity
import android.content.Intent
import android.content.IntentFilter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private var activity: Activity?=null
    private val dynamicBroadcastReceiver=DynamicBroadcastReceiver()
    private val myLocalBroadcastReceiver=MyLocalBroadcastReceiver()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        activity=this
        bt_send_self_br.setOnClickListener{
            //发送自定义广播
            intent= Intent("MySelfBroadcastReceiver")
            sendBroadcast(intent)
        }
        bt_dynamic_br.setOnClickListener{
            //动态广播
            //和清单文件格式对应，这里是添加广播的过滤
            val dynamicIntentFilter=IntentFilter()
            //添加动作，设置广播
            dynamicIntentFilter.addAction("DynamicBroadcastReceiver")
            //动态注册
            registerReceiver(dynamicBroadcastReceiver,dynamicIntentFilter)

            //--------------------------------------------------
            //发送广播测试
            intent=Intent("DynamicBroadcaseReceiver")
            sendBroadcast(intent)

        }
        bt_static_br.setOnClickListener{
            //默认即使无序广播
            intent=Intent("StaticBroadcastReceiver")
            sendBroadcast(intent)

            //有序广播：我们可以对其做处理，如拦截之类，
            sendOrderedBroadcast(intent,null)
        }

        bt_local_br.setOnClickListener{
            //获取本地管理者
            val localBroadcastManager=
                    LocalBroadcastManager.getInstance(activity!!)
            //动态注册
            val intentFilter=IntentFilter()
            intentFilter.addAction("MyLocalBroadcastReceiver")
            localBroadcastManager.registerReceiver(
                    myLocalBroadcastReceiver,
                    intentFilter
            )

            //发送广播
            intent=Intent("MyLocalBroadcastReceiver")
            localBroadcastManager.sendBroadcast(intent)

        }

        bt_priority_br.setOnClickListener{
            //优先级测试
            //优先级的测试-这里我们选择静态注册，
            // 也就是直接在清单注册-设置priority
            // 经过测试很明显拦截广播是建立在有序广播的基础上面，
            // 同时拦截广播后只显示静态注册的Toask，而不是优先级的Toask
            intent=Intent("StaticBroadcastReceiver")
            intent.action = "PriorityBroadcastReceiver"
            sendOrderedBroadcast(intent,null)

        }

    }

    override fun onDestroy() {
        super.onDestroy()
        //注销广播-因为不是本地广播的话，会有数据隐患的，
        // 好比你已经关了APP但是还是一直发广播或者接收广播，
        // 系统会自己操作，所以极为不安全，
        unregisterReceiver(dynamicBroadcastReceiver)
        unregisterReceiver(myLocalBroadcastReceiver)
    }
}
